#include "memoryPool.h"
#include <cstring>

MemoryPool::MemoryPool()
{
     
    m_blockHead = nullptr;
    
    m_nodeHead = nullptr;

}

MemoryPool::~MemoryPool()
{
    // 释放所有分配的Block以防止内存泄漏
    while (m_blockHead != nullptr)
    {
        Block* delBlock = m_blockHead;

        m_blockHead = m_blockHead->next;

        delete delBlock;
        
        delBlock = nullptr;
    }
}

/* 分配空间 */
void *MemoryPool::Allocate()
{
    if(m_nodeHead == nullptr)   // 没有多余空间
    {
        /* 开辟大内存 */
        Block * newBlock = new Block;
        /* 清理脏数据 */
        memset(newBlock, 0, sizeof(newBlock));

        /* 连接小内存 */
        for(int idx = 0; idx < NODE_COUNT; idx++)
        {
            newBlock->node[idx].next = &(newBlock->node[idx + 1]);
        }

        /* 最后一个小内存块需要单独处理 */
        newBlock->node[NODE_COUNT - 1].next = nullptr;

        /* 头插 */
        newBlock->next = m_blockHead;
        m_blockHead = newBlock;

        /* 维护连接 */
        m_nodeHead = &(newBlock->node[0]);
    }

    auto ptr = m_nodeHead;
    /* 清楚脏数据 */
    memset(ptr, 0, sizeof(UseNode));
    m_nodeHead = m_nodeHead->next;
    return ptr;
}

/* 释放空间 */
void MemoryPool::free(void *ptr)
{
    if (ptr != nullptr)
    {
        UseNode* node = static_cast<UseNode*>(ptr);
        memset(ptr, 0, sizeof(UseNode));

        node->next = m_nodeHead;
        m_nodeHead = node;  // 将释放的节点放回链表头部
    }
}
